package userdisplays;

import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.Serializable;

import javax.swing.JTextArea;

public class EditableArea extends JTextArea implements MouseListener,
        KeyListener, FocusListener, Serializable, Editable
{
    private static final long serialVersionUID = 1L;
    private UserPanel panel;
    private boolean editable = true;

    public EditableArea(UserPanel p, String s)
    {
        super(s, 5, 10);
        panel = p;
        setEditable(false);
        addMouseListener(this);
        addKeyListener(this);
        addFocusListener(this);
        setWrapStyleWord(true);
    }

    public void mouseClicked(MouseEvent e)
    {
        if (!editable)
            return;

        getCaret().setVisible(true);
        if (e.getButton() == MouseEvent.BUTTON1)
        {
            setEditable(true);
        }
    }

    public void mouseEntered(MouseEvent e)
    {
    }

    public void mouseExited(MouseEvent e)
    {
    }

    public void mousePressed(MouseEvent e)
    {
    }

    public void mouseReleased(MouseEvent e)
    {
    }

    public void focusGained(FocusEvent e)
    {
    }

    public void focusLost(FocusEvent e)
    {
        if (!editable)
            return;
        setEditable(false);
        panel.sendPanel();
    }

    public void lock()
    {
        editable = false;
    }

    public void unlock()
    {
        editable = true;
    }

    public void keyPressed(KeyEvent arg0)
    {
        if (!editable)
            return;
        if (arg0.getKeyCode() == KeyEvent.VK_ENTER)
        {
            if (arg0.isShiftDown())
            {
                int car = this.getCaretPosition();
                String before = this.getText().substring(0, car);
                String after = this.getText().substring(car,
                        this.getText().length());
                this.setText(before + '\n' + after);
                this.setCaretPosition(car + 1);
            }
            else
            {
                setEditable(false);
                panel.sendPanel();
            }
        }
    }

    public void keyReleased(KeyEvent arg0)
    {
    }

    public void keyTyped(KeyEvent arg0)
    {
    }
}